<template>
    <div>
        <a-tooltip :title="['start', 'resume'].includes(speakType) ? '暂停' : '播报'">
            <a-button @click="handClick">
                <a-icon type="pause" v-if="['start', 'resume'].includes(speakType)" />
                <a-icon type="caret-right" v-else />
            </a-button>
        </a-tooltip>
    </div>
</template>
<script>
import { strString } from './static';

export default {
    name: 'Speak',
    props: {
        text: {
            type: String
        },
        item: {
            type: [Object]
        },
        type: {
            type: String,
        }
    },
    data() {
        return {
            value: '',
            synth: window.speechSynthesis,
            msg: new SpeechSynthesisUtterance(),
            speakType: 'end',
        }
    },
    mounted() {
        this.msg.addEventListener('start', (event) => {
            this.speakType = 'start'
        });
        this.msg.addEventListener('pause', (event) => {
            this.speakType = 'pause'
        });

        this.msg.addEventListener('resume', (event) => {
            this.speakType = 'resume'
        });

        this.msg.addEventListener('end', (event) => {
            this.speakType = 'end'
        });

        this.msg.addEventListener('error', (event) => {
            this.speakType = 'error'
        });

    },
    methods: {
        handClick() {
            if (['start', 'resume'].includes(this.speakType)) {
                this.handleStop();
            } else if (['end', 'error'].includes(this.speakType)) {
                this.handleSpeak();
            } else if (['pause'].includes(this.speakType)) {
                this.handlerResume();
            }
        },
        handlerResume() {
            this.synth.resume();
        },
        handleSpeak(text) {
            this.msg.text = text || this.value;
            this.msg.lang = "zh-CN";  // 使用的语言:中文
            this.msg.volume = 1;      // 声音音量：1
            this.msg.rate = 1;        // 语速：1
            this.msg.pitch = 1;       // 音高：1
            this.synth.speak(this.msg);    // 播放
        },
        handleStop() {
            this.synth.cancel();
        }
    },
    beforeDestroy() {
        this.handleStop();
        this.$nextTick(() => {
            window.removeEventListener('start', () => { });
            window.removeEventListener('pause', () => { });
            window.removeEventListener('resume', () => { });
            window.removeEventListener('end', () => { });
            window.removeEventListener('error', () => { });
        })
    },
    watch: {
        item: {
            handler(nVal, Oval) {
                let str = strString(this.type, nVal);
                this.value = str;
            },
            immediate: true,
            deep: true,
        },
    }
}
</script>
<style lang="less" scoped></style>